<style lang="less">
.resource {
    font-size:12px;
    .paths {
        padding:0 5px;
        border: 1px solid #ddd;
        border-bottom:0;
        background-color:#f8f8f8;
        .path-item {
            cursor:pointer;
            &:hover {
                border-color: rgb(43, 143, 236);
                background-color: rgb(226, 241, 243);
            }
        }
    }
    .item-container {
        border:1px solid #ddd;
        padding:5px;
        .list-item {
            position: relative;
            border-bottom:1px solid #e8e8e8;
            cursor:pointer;
            line-height: 28px;
            &:hover {
                background-color: rgb(226, 241, 243);
            }
            &-operation {
                position: absolute;
                display: block;
                top: 3px;
                right: 1px;
            }
        }
        .thumbnail-item {
            position: relative;
            display:inline-block;
            height:120px;
            width:120px;
            border:1px solid #e8e8e8;
            cursor:pointer;
            margin:5px;
            background-repeat: no-repeat;
            background-position:center center;
            background-size: cover;
            &:hover {
                border-color: rgb(43, 143, 236);
                background-color: rgb(226, 241, 243);
            }
            &-name {
                position: absolute;
                display: block;
                top: 0;
                left: 0;
                right: 0;
                background-color: rgba(0, 0, 0, .2);
                color: white;
            }
            &-operation {
                position: absolute;
                display: block;
                width: 100%;
                left: 0;
                bottom: 0;
            }
            &-checkbox {
                position: absolute;
                display: block;
                top: 0;
                right: 0;
            }
        }
    }
}
</style>
<template>
<div>
    <Row class="resource">
        <Col span="24" style="padding:5px 0;">
            <ButtonGroup size="small">
                <Button @click="toPrevPath" :disabled="!hasPrevPath" title="后退">
                    <Icon type="ios-arrow-back" />
                </Button>
                <Button @click="toNextPath" :disabled="!hasNextPath" title="前进">
                    <Icon type="ios-arrow-forward" />
                </Button>
            </ButtonGroup>
            <RadioGroup v-model="theShowType" type="button" size="small" style="padding-left:5px;">
                <Radio label="list" style="padding:0 4px;" :disabled="theShowType=='list'" title="列表显示">
                    <Icon type="ios-list"/>
                </Radio>
                <Radio label="thumbnail" style="padding:0 4px;" :disabled="theShowType=='thumbnail'" title="缩略图显示">
                    <Icon type="ios-apps" />
                </Radio>
            </RadioGroup>
            <ButtonGroup v-if="theOperable" size="small" style="float:right;">
                <Button title="新建文件夹" @click="handleShowCreateFolderModel">
                    <Icon type="ios-folder-open" />
                </Button>
                <Button title="新建文件" @click="handleShowCreateFileModel">
                    <Icon type="ios-document-outline" />
                </Button>
                <Button title="批量删除" v-if=false>
                    <Icon type="ios-trash-outline" />
                </Button>
                <Button title="批量移动到" v-if=false>
                    <Icon type="md-arrow-forward" />
                </Button>
            </ButtonGroup>
            <Upload v-if="theOperable" style="float:right;"
                :action="action"
                :headers="headers"
                :data="uploadData"
                :show-upload-list="false"
                :format="extensions"
                :max-size="2048"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                :on-progress="handleOnProgress"
                :on-success="handleSuccess">
                <Button size="small" title="上传文件">
                    <Icon type="ios-cloud-upload-outline" />
                </Button>
            </Upload>
            <Progress v-if="uploadModel.showProgress" :percent="uploadModel.percentage" :stroke-width="5" style="width:200px;float:right;line-height:28px;"></Progress>
        </Col>
        <Col span="24" class="paths">
            <span v-for="(item, index) in currentPaths" :key="index" @click="toPath(index)" class="path-item">/{{item.name}}</span>
        </Col>
        <Col span="24" class="item-container">
            <div v-if="items.length==0" style="text-align:center;color:#888;">无资源</div>
            <div v-if="theShowType=='list'">
                <p v-for="(item, index) in items" v-if="item.isFolder" :key="index" class="list-item">
                    <Checkbox v-if="theSelectable!='file'" v-model="item.selected" @on-change="handleOnSelectChange"></Checkbox>
                    <span @click="handleGetAll(item.id, item.displayName)">
                        <Icon type="ios-folder-open" />
                        {{item.displayName}}
                    </span>
                    <span v-if="theOperable" class="list-item-operation">
                        <ButtonGroup size="small" style="float:right;">
                            <Button title="编辑" @click="handleShowUpdateFileModel(item)">
                                <Icon type="ios-create-outline" />
                            </Button>
                            <Button title="删除" @click="handleDelete(item)">
                                <Icon type="ios-trash-outline" />
                            </Button>
                            <Button title="移动到" v-if=false>
                                <Icon type="md-arrow-forward" />
                            </Button>
                        </ButtonGroup>
                    </span>
                </p>
                <p v-for="(item, index) in items" v-if="!item.isFolder" :key="index" class="list-item">
                    <Checkbox v-if="theSelectable!='folder'" v-model="item.selected" @on-change="handleOnSelectChange"></Checkbox>
                    <span>
                        <Icon type="ios-document-outline" />
                        {{item.displayName}}
                    </span>
                    <span v-if="theOperable" class="list-item-operation">
                        <ButtonGroup size="small" style="float:right;">
                            <Button title="编辑" @click="handleShowUpdateFileModel(item)">
                                <Icon type="ios-create-outline" />
                            </Button>
                            <Button title="删除" @click="handleDelete(item)">
                                <Icon type="ios-trash-outline" />
                            </Button>
                            <Button title="移动到" v-if=false>
                                <Icon type="md-arrow-forward" />
                            </Button>
                        </ButtonGroup>
                    </span>
                </p>
            </div>
            <div v-else-if="theShowType=='thumbnail'">
                <div v-for="(item, index) in items" v-if="item.isFolder" :key="index" class="thumbnail-item">
                    <div style="height:100%;" @click="handleGetAll(item.id, item.displayName)">
                        <span class="thumbnail-item-name">
                            <Icon type="ios-folder-open" />
                            {{item.displayName}}
                        </span>
                    </div>
                    <span v-if="theOperable" class="thumbnail-item-operation">
                        <ButtonGroup size="small" style="float:right;">
                            <Button title="编辑" @click="handleShowUpdateFileModel(item)">
                                <Icon type="ios-create-outline" />
                            </Button>
                            <Button title="删除" @click="handleDelete(item)">
                                <Icon type="ios-trash-outline" />
                            </Button>
                            <Button title="移动到" v-if=false>
                                <Icon type="md-arrow-forward" />
                            </Button>
                        </ButtonGroup>
                    </span>
                    <span v-if="theSelectable!='file'" class="thumbnail-item-checkbox">
                        <Checkbox v-model="item.selected" @on-change="handleOnSelectChange"></Checkbox>
                    </span>
                </div>
                <div v-for="(item, index) in items" v-if="!item.isFolder" :key="index" class="thumbnail-item" :style="{'background-image':`url(${item.url})`}">
                    <div style="height:100%;">
                        <span class="thumbnail-item-name">
                            <Icon type="ios-document-outline" />
                            {{item.displayName}}
                        </span>
                    </div>
                    <span v-if="theOperable" class="thumbnail-item-operation">
                        <ButtonGroup size="small" style="float:right;">
                            <Button title="编辑" @click="handleShowUpdateFileModel(item)">
                                <Icon type="ios-create-outline" />
                            </Button>
                            <Button title="删除" @click="handleDelete(item)">
                                <Icon type="ios-trash-outline" />
                            </Button>
                            <Button title="移动到" v-if=false>
                                <Icon type="md-arrow-forward" />
                            </Button>
                        </ButtonGroup>
                    </span>
                    <span v-if="theSelectable!='folder'" class="thumbnail-item-checkbox">
                        <Checkbox v-model="item.selected" @on-change="handleOnSelectChange"></Checkbox>
                    </span>
                </div>
            </div>
        </Col>
        <Col span="24">
            <AutoPage v-model="page" :auto="false" style="text-align:right;" ></AutoPage>
        </Col>
    </Row>

	<Modal v-model="showCreateFileModal" title="添加资源" :mask-closable="false">
		<Form ref="create-file-form" :model="createFileModel" :label-width="100">
			<FormItem label="名称" prop="displayName" required>
				<Input v-model="createFileModel.displayName" />
			</FormItem>
			<FormItem label="地址" prop="path" required>
				<Input v-model="createFileModel.path" />
			</FormItem>
		</Form>
        <div slot="footer">
            <Button type="primary" @click="handleCreateFile">新建</Button>
            <Button @click="showCreateFileModal=false">取消</Button>
        </div>
	</Modal>

	<Modal v-model="showUpdateFileModal" title="编辑资源" :mask-closable="false">
		<Form ref="update-file-form" :model="updateFileModel" :label-width="100">
			<FormItem label="名称" prop="displayName" required>
				<Input v-model="updateFileModel.displayName" />
			</FormItem>
		</Form>
        <div slot="footer">
            <Button type="primary" @click="handleUpdateFile">保存</Button>
            <Button @click="showUpdateFileModal=false">取消</Button>
        </div>
	</Modal>
</div>
</template>

<script lang="ts">
import Page from '../models/Page';
import AutoPage from '../components/AutoPage'
import URL from '../lib/url'
import ajax from '../lib/ajax'

export default {
    props: {
        isOnlyFolder: {
            type: Boolean,
            default: false
        },
        fileType: {
            type: Number,
            default: 0 // 0:all, 1:image, 2:document, 3:video
        },
        showType: {
            type: String,
            default: "thumbnail" // list, thumbnail
        },
        operable: {
            type: Boolean,
            default: true
        },
        selectable: {
            type: String,
            default: "all" // all, file, folder
        }
    },
    components: {
        AutoPage
    },
    data() {
        return {
            page: new Page('/api/services/app/FileSystem/Search'),
            theOperable: this.operable,
            theSelectable: this.selectable,
            theShowType: this.showType,
            theFileType: this.fileType,
            paths: [],
            currentPathIndex: -1,
            items: [],
            uploadModel: {
                showProgress: false,
                percentage: 0
            },
            createFolderModel: {
                displayName: '',
                parentId: null
            },
            showCreateFileModal: false,
            createFileModel: {
                path: '',
                labels: [],
                displayName: '',
                parentId: null
            },
            showUpdateFileModal: false,
            updateFileModel: {
                labels: [],
                displayName: ''
            }
        }
    },
    computed: {
        action() {
            return URL.remoteUrl + 'api/FileSystem/Upload'
        },
        extensions() {
            var image = ['png', 'jpeg', 'jpg'];
            var doc = ['doc', 'docx', 'txt', 'xls', 'xlsx'];
            var video = ['mp4'];

            switch(this.theFileType) {
                case 'all': return image.concat(doc, video);
                case 'image': return image;
                case 'document': return doc;
                case 'video': return video;
            }

            return [];
        },
        headers() {
            var headers = {};
            if(!!window.abp.auth.getToken()){
                headers["Authorization"]="Bearer "+window.abp.auth.getToken();
            }
            headers[".AspNetCore.Culture"]=window.abp.utils.getCookieValue("Abp.Localization.CultureName");
            headers["Abp.TenantId"]=window.abp.multiTenancy.getTenantIdCookie();
            return headers;
        },
        uploadData() {
            if(this.currentPath.id) {
                return {
                    parentId: this.currentPath.id
                };
            }else {
                return {};
            }
        },
        // 被选择的项
        selectedItems() {
            var temp = [];
            this.items.forEach(item => {
                if(item.selected == true) {
                    temp.push(Object.assign({}, item));
                }
            });
            return temp;
        },
        // 是否有上一级
        hasPrevPath() {
            return this.currentPathIndex > 0;
        },
        // 是否有下一级
        hasNextPath() {
            return this.currentPathIndex < this.paths.length - 1;
        },
        // 当前路径数组
        currentPaths() {
            var temp = [];
            for(var i = 0; i < this.paths.length; i++) {
                if(i <= this.currentPathIndex) {
                    temp.push(this.paths[i]);
                }
            }
            return temp;
        },
        currentPath() {
            return this.paths[this.currentPathIndex];
        }
    },
    methods: {
        confirm(content, okFunc) {
            this.$Modal.confirm({
                title: '提示',
                content: content,
                okText: '确认',
                cancelText: '取消',
                onOk:async()=>{
                    okFunc();
                }
            })
        },
        // 文件上传相关
        handleFormatError (file) {
            this.$Notice.warning({
                title: '错误的文件格式',
                desc: `文件${file.name}格式错误，请选择[ ${this.extensions.join(", ")} ]中的文件格式`
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '超过文件大小限制',
                desc: '文件' + file.name + '过大，不超过2M'
            });
        },
        handleBeforeUpload () {
            this.uploadModel.showProgress = true;
            return true;
        },
        handleOnProgress(event, file, fileList) {
            this.uploadModel.percentage = file.percentage;
        },
        handleSuccess (res, file) {
            this.uploadModel.showProgress = false;
            this.uploadModel.percentage = 0;
            this.getCurrentPathData();
        },
        // 得到指定id下的文件夹和文件
        handleGetAll(parentId, name) {
            this.getData(parentId);
            this.insertPath(parentId, name);
        },
        // 从localStroage获取路径
        initPaths() {
            var paths = [{id:null, name:"资源库"}];
            var temp = localStorage["resource-core"];
            if(temp) {
                paths = JSON.parse(temp);
            }
            this.paths = paths;
            this.toPath(paths.length - 1);
        },
        // 将路径存入localStroge
        storagePaths(paths) {
            localStorage["resource-core"] = JSON.stringify(this.currentPaths);
        },
        // 到指定的一级
        toPath(index) {
            if(index == this.currentPathIndex) return;
            if(index >= 0 && index < this.paths.length) {
                this.getData(this.paths[index].id);
                this.currentPathIndex = index;
                this.storagePaths();
            }
        },
        // 上一级
        toPrevPath() {
            this.toPath(this.currentPathIndex - 1);
        },
        // 下一级
        toNextPath() {
            this.toPath(this.currentPathIndex + 1);
        },
        // 插入新的路径
        insertPath(id, name) {
            var temp = [];
            for(var i = 0; i < this.paths.length; i++) {
                if(i <= this.currentPathIndex) {
                    temp.push(this.paths[i]);
                }else {
                    break;
                }
            }
            temp.push({id: id, name: name});
            this.paths = temp;
            this.toPath(temp.length - 1);
        },
        handleOnSelectChange(value) {
            this.$emit('on-select-change', this.selectedItems);
        },
        clearSelect() {
            this.items.forEach(item => item.selected = false);
        },
        handleShowCreateFolderModel () {
            this.createFolderModel.parentId = this.currentPath.id || null;
            this.$Modal.confirm({
                render: (h) => {
                    return h('Input', {
                        props: {
                            value: this.createFolderModel.displayName,
                            autofocus: true,
                            placeholder: '请输入文件夹名称',
                            required: true
                        },
                        on: {
                            input: (val) => {
                                this.createFolderModel.displayName = val;
                            }
                        }
                    })
                },
                onOk: this.handleCreateFolder
            })
        },
        async handleCreateFolder() {
            var response = await ajax.post('/api/services/app/FileSystem/CreateFolder', this.createFolderModel);
            if(response.data.success) {
                this.getCurrentPathData();
            }
        },
        handleShowCreateFileModel() {
            this.createFileModel.parentId = this.currentPath.id || null;
            this.showCreateFileModal = true;
        },
        async handleCreateFile() {
            this.$refs["create-file-form"].validate(async (valid) => {
                if(valid) {
                    var response = await ajax.post('/api/services/app/FileSystem/Create', this.createFileModel);
                    if(response.data.success) {
                        this.getCurrentPathData();
                        this.showCreateFileModal = false;
                    }
                }
            });
        },
        handleShowUpdateFileModel(item) {
            this.updateFileModel = Object.assign({}, item);
            this.showUpdateFileModal = true;
        },
        async handleUpdateFile() {
            this.$refs["update-file-form"].validate(async (valid) => {
                if(valid) {
                    var response = await ajax.put('/api/services/app/FileSystem/Update', this.updateFileModel);
                    if(response.data.success) {
                        this.getCurrentPathData();
                        this.showUpdateFileModal = false;
                    }
                }
            });
        },
        handleDelete(item) {
            this.confirm(`确认删除${item.displayName}吗？`, async () => {
                var response = await ajax.post('/api/services/app/FileSystem/Delete', { id: item.id });
                if(response.data.success) {
                    this.getCurrentPathData();
                }
            })
        },
        // 获取数据
        getData(parentId) {
            this.page.action_data = {
                parentId: parentId || null,
                isOnlyForder: this.isOnlyForder,
                fileType: this.theFileType
            };
            this.page.getData();
        },
        getCurrentPathData() {
            this.getData(this.currentPath.id);
        }
    },
    created() {
        this.page.afterGetData.push(result => {
            if(!result) return;
            var temp = [];
            result.items.forEach(item => {
                temp.push(Object.assign({ selected: false }, item));
            });
            this.items = temp;
        });
        this.initPaths();
        // this.theOperable = false;
        // this.theSelectable = 'file';
    }
}
</script>
